/*
 * @Author: yuqy
 * @Date: 2023-04-11 16:02:46
 * @LastEditors: yuqy
 * @LastEditTime: 2023-10-31 15:55:00
 * @Descripttion: -
 */
import { createRouter, createWebHistory } from 'vue-router'
// createWebHashHistory
// createWebHashHistory
// 公共基础路由
import routes from './routes'
// 顶部页面加载进度条
import NProgress from 'nprogress'
import { erroList, menuList } from "@/libs/menu";
import util from '@/libs/util'
import store from "@/store";
let modules = import.meta.glob('../view/**/*.vue')
import "@/assets/less/nprogress.less";
const NProgressOption = {
    easing: 'ease', 
    speed: 500,
    showSpinner: true
}
NProgress.configure(NProgressOption);

// 路由的基础路径
let VITE_APP_BASE_URL = import.meta.env.VITE_APP_BASE_URL;
const route = createRouter({
    history: createWebHistory(VITE_APP_BASE_URL),
    base: '/',
    routes
})

let isLoading = false
// 免登陆路由名单
const NO_LOGIN = ['audience', 'demo', 'demoSet', 'menu', 'whiteboardOnline', 'login', 'error_500', 'error_404']
// 路由前置钩子
route.beforeEach(async (to, form, next) => {
    let name = to.name
    const Token = util.getToken()
    NProgress.start()
    if (!isLoading) {
        isLoading = true
        menuList.forEach(s => {
            if (s.redirect) {
                route.addRoute({
                    path: s.path,
                    meta: {},
                    name: s.name,
                    redirect: s.redirect
                })
            } else {
                route.addRoute({
                    path: s.path,
                    meta: {},
                    name: s.name,
                    component: modules[`../view${s.url}.vue`]
                })
            }
            if (s.children && s.children.length > 0) {
                s.children.forEach(p => {
                    route.addRoute(s.name, {
                        path: p.path,
                        meta: {},
                        name: p.name,
                        component: modules[`../view${p.url}.vue`]
                    })
                })
            }
        })
        // 加载捕获异常的路由
        erroList.forEach(s => {
            route.addRoute({
                path: s.path,
                name: s.anme,
                redirect: s.redirect
            })
        })
        next({ path: to.path, query: to.query })
    } else {
        try {
            if (NO_LOGIN.includes(name))  return next() 
            let userInfo = store.state.user.userInfo
            if (Token) {
                if (Object.keys(userInfo).length == 0) { // 用户信息不存在
                    await store.dispatch('user/getUserInfo')
                }
                return next() 
            } else {
                next({ name: 'login' })  
            }
        } catch (error) {
            next({ name: 'error_500' })
        }  
    }
})

// 路由加载结束
route.afterEach(() => {
    NProgress.done()
})
export default route